<template>
  <div>
    <PDFContainer ref='PDFContainer' :page-width='1120'>
      <div class='town-pdf-report-table-container'>
        <div class='flex-contain text-align-center marBottom10 width100 flex-justify-content-center font-size-16 font-bold'>生活小区（公寓）雨污分流、截污纳管情况调查表</div>
        <div class='house-list' v-for='(house, index) in ruleForm' :key='index'>
          <div class='house'>
            <table class='town-pdf-report-table'>
              <tr>
                <td>乡镇（街道）</td>
                <td :colspan='3'>{{ house.areaName }}</td>
              </tr>
              <tr>
                <td>社区（城中村、镇中村）</td>
                <td :colspan='3'>{{ house.communityLabel }}</td>
              <tr/>
              <tr>
                <td>小区名称</td>
                <td>{{ house.townName }}</td>
                <td>小区地址</td>
                <td>{{ house.position }}</td>
              <tr/>
              <tr>
                <td>联系人</td>
                <td>{{ house.contactName }}</td>
                <td>联系电话（街道）</td>
                <td>{{ house.contactTel }}</td>
              </tr>
              <tr>
                <td>建成时间</td>
                <td>{{ house.buildDate }}</td>
                <td>房屋幢数</td>
                <td></td>
              </tr>
              <tr>
                <td>户数</td>
                <td>{{ house.householdNum }}</td>
                <td>常驻人口数</td>
                <td>{{ house.permanentPopulation }}</td>
              </tr>
              <tr>
                <td>房屋总占地面积</td>
                <td><span class='text-underline'>{{ house.housingArea }}</span>平方米</td>
                <td>房屋总建筑面积</td>
                <td><span class='text-underline'>{{ house.buildingArea }}</span>平方米</td>
              </tr>
              <tr>
                <td>竣工图纸</td>
                <td>
                  <input type='checkbox' :checked='house.jgtz'>有</input>
                  <br/>
                  <input type='checkbox' :checked='!house.jgtz'>无</input>
                </td>
                <td>图纸与现场是否匹配</td>
                <td>
                  <input type='checkbox' :checked='house.tzyxc'>是</input>
                  <br/>
                  <input type='checkbox' :checked='!house.tzyxc'>否</input>
                </td>
              </tr>
              <tr>
                <td>周边市政管网配套</td>
                <td>
                  <input type='checkbox' :checked='house.zbsz'>是</input>
                  <br/>
                  <input type='checkbox' :checked='!house.zbsz'>否</input>
                </td>
                <td>是否正确接入市政管网</td>
                <td>
                  <input type='checkbox' :checked='house.sfzqjrscgw'>是</input>
                  <br/>
                  <input type='checkbox' :checked='!house.sfzqjrscgw'>否</input>
                </td>
              </tr>
              <tr>
                <td :rowspan='3' >“三水”是否规范接入污水管网</td>
                <td :colspan='3' style='text-align: left'>
                  <div class='custom-check-box'>
                    <div class='title'>厨房废水</div>
                    <div class='check-group'>
                      <input type='checkbox' :checked='house.cffs'>是</input>
                      <input type='checkbox' :checked='!house.cffs'>否</input>
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <td :colspan='3' style='text-align: left' >
                  <div class='custom-check-box'>
                    <div class='title'>卫生间污水</div>
                    <div class='check-group'>
                      <input type='checkbox' :checked='house.wsjws'>是</input>
                      <input type='checkbox' :checked='!house.wsjws'>否</input>
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <td :colspan='3' style='text-align: left' >
                  <div class='custom-check-box'>
                    <div class='title'>阳台洗衣污水</div>
                    <div class='check-group'>
                      <input type='checkbox' :checked='house.ytxyws'>是</input>
                      <input type='checkbox' :checked='!house.ytxyws'>否</input>
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <td>“化粪池（沼气池） 数量</td>
                <td>{{ house.digesterCount }}</td>
                <td>小区物业管理情况</td>
                <td style='text-align: left'>
                  <input type='checkbox'>物管（企业）</input>
                  <br/>
                  <input type='checkbox'>业主委员会</input>
                  <br/>
                  其他：<span class='text-underline'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                </td>
              </tr>
              <tr style='height: 60px'>
                <td >化粪池污水排放情况</td>
                <td style='text-align: left'>
                  <input type='checkbox' :checked='house.jrysg'>接入雨水管</input>
                  <br/>
                  <input type='checkbox' :checked='house.jrwsgw'>接入污水管网</input>
                  <br/>
                  <input type='checkbox' :checked='house.zpwhj'>直排（渗透）外环境</input>
                </td>
                <td>其他情况</td>
                <td>{{ house.otherSituation }}</td>
              </tr>
              <tr style='height: 60px'>
                <td>管道接驳问题数</td>
                <td :colspan='3' style='text-align: left'>
                  <div v-html="
                    (house.quesFormatter || []).map((x, index) => '<span>' + x.label + '</span>' + '<span class=\'text-underline\'>   ' + x.value + '   </span><span>处  </span><br/>'
                    + ((index === (house.quesFormatter || []).length - 1) ? '<span>其他：</span>' : '')).join('')
                  " />
                </td>
              </tr>
              <tr style='height: 30px'>
                <td :colspan='4' style='text-align: left'>
                  提供（绘制）地下排水管网示意图
                  <br/>
                  （标注窨井盖、化粪池（沼气池）、雨污水管网及流向、管径、与市政管网接入点）
                </td>
              </tr>
              <tr>
                <td :colspan='4'>存在问题影像资料</td>
              </tr>
              <tr class='town-pdf-report-table-footer'>
                <td :colspan='4'>调查单位：浙江华创设计有限公司
                  调查人 （签字）：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  调查日期：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                </td>
              </tr>
            </table>
            <!-- 图片区域 -->
            <div class='list-item'>
              <div class='item' v-for='(item, index) in (house.pics || [])' :key='index'>
                <img :src="item.base64" crossorigin="anonymous" style='width: 100%;height:100%;' />
                <img :src="item.picUrl" crossorigin="anonymous" style='width: 100%;height: 300px;' />
              </div>
            </div>
          </div>
        </div>
      </div>
    </PDFContainer>
  </div>
</template>

<script>
import PDFContainer from '@/components/PDF/PDF.vue'
import { townInitDataRep } from '@/api/Town'
import { getDictList, getDictItemList } from '@/api/system'
// import { fileToBase64, picToBase64 } from '@/utils/fun'
import { getUrlFile } from '@/api/system'
import { blobUrlToBase64 } from '@/utils/fun'

const DEFAULT_RULEFORM = []
export default {
  components: {
    PDFContainer
  },
  props: {
    townId: {
      type: [String, Number], // Number id 注意精度丢失，值会发生改变
      default: ''
    }
  },
  data() {
    return {
      ruleForm: JSON.parse(JSON.stringify(DEFAULT_RULEFORM)),
      checkList: [{
        label: '有',
        value: 1
      },{
        label: '无',
        value: 0
      }],
      checkList2: [{
        label: '是',
        value: 1
      },{
        label: '否',
        value: 0
      }],
      questionTypeList: []
    }
  },
  watch: {
    townId: {
      handler(v) {
        this.getDetailData()
      }
    },
    immediate: true,
    deep: true
  },
  methods: {
    async getDictListFun() {
      // 获取问题类型枚举
      const params = {
        dictCode: "ps_house_question_type",
        pageNo: 1,
        pageSize: 1
      }
      await getDictList(params).then(async (res) => {
        const dictId  = (res.result.records || [])[0].id
        if (dictId) {
          const params = {
            dictId
          }
          await getDictItemList(params).then((res) => {
            this.questionTypeList = (res.result.records || []).map(x => {
              return {
                name: x.itemText,
                value: x.itemValue,
              }
            })
          })
        }
      })
    },
    boolFormat(data) {
      return (data === '1' || data === 1) ? '是' : '否'
    },
    boolFormat2(data) {
      return (data === '1' || data === 1) ? '有' : '无'
    },
    async getBase64Pic(picData, resolve) {
      const params = {
        url: picData.picUrl
      }
      let blob
      await getUrlFile(params).then((res) => {
        // console.log('blob')
        blob = window.URL.createObjectURL(new Blob([res],{type:'image/png'}))
      })
      await blobUrlToBase64(blob).then((res) => {
        // console.log(res, 'res')
        picData.base64 = res
        if (resolve) {
          resolve()
        }
      })
    },
    async getDetailData() {
      let flag = true
      let ruleForm = JSON.parse(JSON.stringify(DEFAULT_RULEFORM))
      if (this.townId) {
        // 获取字典
        await this.getDictListFun()

        // 获取数据
        const params = new window.FormData();
        params.append('townId', this.townId)
        await townInitDataRep(params).then((res) => {
          // 格式化内容
          ruleForm = (res.result || []).map((house) => {
            try {
              house.pics = JSON.parse(house.pics)
            } catch (e) {
              house.pics = []
            }

            house.quesFormatter = this.questionTypeList.map(x => {
              const tar = (house.ques || []).find(y => (y.quesType + '') === (x.value + ''))
              if (tar) {
                return {
                  label: x.name,
                  value: tar.queCount
                }
              }
              return {
                label: x.name,
                value: 0
              }
            })
            return house
          });

          // 测试
          // ruleForm = [(ruleForm || [])[0]]

        }).catch(e => {
          flag = false
          console.log(e, 'e')
        })
      };

      // 将 图片数据转化为 base64 编码，解决跨域问题
      const list = [];

      (ruleForm || []).map((house) => {
        (house.pics || []).map((picData) => {
          list.push(new Promise(async (resolve, reject) => {
            await this.getBase64Pic(picData, resolve)
          }))
        })
      })

      // console.log(list, 'list')

      const promise = Promise.all(
        await list
      );

      await promise.then(() => {
        // console.log('test1')
      }).catch(e => {
        console.log(e, 'e')
      });

      // console.log('test2')

      this.ruleForm = ruleForm
      // console.log(this.ruleForm, 'this.ruleForm')

      if (!flag) {
        // 提示异常
        return
      }

      // 测试
      // return

      this.exportPages()
    },
    // 计算统计数据，从房屋到合并到小区
    calcTotalData(data) {
      const result = { };
      let householdNum = 0 // 户数总计
      let permanentPopulation = 0 // 常住人口数
      let housingArea = 0 // 占地面积
      let buildingArea = 0 // 房屋建筑面积
      const pics = []; // 图片列表
      (data || []).map(house => {
        householdNum += house.householdNum;
        permanentPopulation += house.permanentPopulation;
        housingArea += house.housingArea;
        buildingArea += house.buildingArea;
        (house.pics || []).map(questionStr => {
          let question = questionStr
          try {
            question = JSON.parse(questionStr)
          } catch (e) {
            question = []
          }
          (question || []).map(picData => {
            pics.push(picData.picUrl)
          })
        })
      });
      return {
        pics,
        householdNum,
        permanentPopulation,
        housingArea,
        buildingArea,
        fwzs: (data || []).length
      }
    },
    exportPages() {
      // 导出
      const ref = this.$refs.PDFContainer
      if (ref) {
        // 导出为pdf
        ref.exportPages()
      }
    }
  }
}
</script>

<style lang='less' scoped>
.town-pdf-report-table-container {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: 10px 20px;
  background: white;
}
.town-pdf-report-table {
  width: 100%;
  min-width: 100%;
  border: none !important;
  /*border-right: 1px solid #000000;
  border-bottom: 1px solid #000000;
  border-collapse: separate;
  border-spacing: 0;*/
  tr {
    display: table-row;
    vertical-align: inherit;
    border-color: inherit;
    border-top: 1px solid #000000;
    border-left: 1px solid #000000;
    td {
      border-right: 1px solid #000000;
      padding: 11px 8px;
      overflow-wrap: break-word;
      /*color: rgba(0, 0, 0, 0.85);*/
      font-weight: 500;
      text-align: center;
      vertical-align: middle;
      border-bottom: 1px solid #000000;
      /*transition: background 0.3s ease;*/
      white-space: nowrap;
      word-break: break-word;
    }
  }
  .town-pdf-report-table-footer {
    border: none !important;
    td {
      border-top: 1px solid #000000 !important;
      border-right: none !important;
      border-bottom: none !important;
      border-left: none !important;
    }
  }
}
.custom-check-box {
  display: flex;
  .check-group {
    margin: auto 50px auto auto;
  }
}
.img-iframe {
  height: 600px !important;
  ::v-deep {
    img {
      width: 100%;
    }
  }
}
</style>